package net.sf.rose.business.action.base;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.rose.business.bean.base.Group;
import net.sf.rose.business.service.GroupSevice;
import net.sf.rose.jdbc.service.Service;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author fengjian
 * @since 2014/03/06
 */
@Controller
@RequestMapping("base/com")
public class GroupConsultController {

	private static String LIST_PAGE = "base/com/group_consult";

	/**
	 * 
	 */
	@RequestMapping("/group_consult.html")
	public ModelAndView list(HttpServletRequest request, Service service, String groups) {
		Map<String, String> map = new HashMap<String, String>();
		if (groups != null && !groups.equals("")) {
			String[] array = StringUtils.split(groups, ',');
			for (String str : array) {
				map.put(str, str);
			}
		}
		ModelAndView mav = new ModelAndView(LIST_PAGE);
		Group group = GroupSevice.getRoot();
		StringBuilder sb = new StringBuilder();
		this.addGroup(sb, group, map);
		mav.addObject("group", sb.toString());
		return mav;
	}

	private void addGroup(StringBuilder sb, Group group, Map<String, String> map) {
		sb.append("<li><a tvalue=\"" + group.getId() + "\" ");
		if (map.get(group.getId()) != null) {
			sb.append("checked=\"true\"");
		}
		sb.append(">").append(group.getText()).append("</a>");
		if (group.getChildGroup().size() > 0) {
			sb.append("<ul>");
			for (Group child : group.getChildGroup()) {
				this.addGroup(sb, child, map);
			}
			sb.append("</ul>");
		}
		sb.append("</li>");
	}

}
